<template>
  <div>
    <el-form
      :model="form"
      :rules="rules"
      ref="form"
      label-position="top"
      
      class="demo-ruleForm service_form"
    >
      <!-- <el-form-item label="上级部门" prop="serviceProviderName">
        <biz-team-select
          :value="tagName"
          collapse
          @input="treeUpdate"
          url="/serviceProvider/tree"
        />
      </el-form-item> -->
      <el-form-item :label="$t('common.fields.providerName.displayName')" prop="serviceProviderName">
        <el-input
          v-model="form.serviceProviderName"
          :placeholder="$t('common.placeholder.inputCompanyName')"
        ></el-input>
      </el-form-item>
      <el-form-item :label="$t('common.fields.serviceProviderType.displayName')" prop="serviceProviderAttribute">
        <el-select
          v-model="form.serviceProviderAttribute"
          :placeholder="$t('common.base.pleaseSelect')"
        >
          <el-option
            v-for="item in serviceProviderAttribute"
            :key="item.id"
            :label="item.name"
            :value="item.name"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('common.base.companyName_1')" prop="registerCompanyName">
        <div style="display:flex;position: relative;">

          <el-input
            v-model="filterParams.keyword"
            clearable
            @blur="iptBlur"
            @focus="iptFocus"
            @clear="iptClear"
          ></el-input>
          
          <div v-if="filterFlag" class="infinite-box">
            <ul v-if="filterData.list.length > 0" v-infinite-scroll="load" class="infinite-list" style="overflow:auto">
              <li @click="getItem(item)" v-for="(item,i) in filterData.list" :key="i">{{ item.label }}</li>
            </ul>
            <div v-else class="register-empty">{{ isEmptyLoading ? `${$t('common.base.loading')}...` : $t('common.base.tip.noData') }}</div>
          </div>
          
        <el-button @click="btnFilter" type="plain-third" class="action-btn">{{$t('common.base.queryCompany')}}</el-button>
        </div>
      </el-form-item>
      <el-form-item :label="$t('common.base.usci')" prop="creditCode">
        <el-input disabled v-model="form.creditCode"></el-input>
      </el-form-item>
      <el-form-item :label="$t('common.fields.serviceProviderLegalRepresentative.displayName')">
        <el-input
          v-model="iptLegalPerson"
          :placeholder="$t('common.fields.serviceProviderLegalRepresentative.placeholder')"
        ></el-input>
      </el-form-item>
      <el-form-item :label="$t('common.fields.serviceProviderRegisterAddress.displayName')" prop="creditCode">
        <form-address
          :field="filedMap.tagAddress"
          v-model="form.tagAddress"
          :placeholder="$t('common.fields.serviceProviderRegisterAddress.placeholder')"
        />
      </el-form-item>
      <el-form-item :label="$t('common.fields.serviceProviderConstractArea.displayName')" prop="tagPlaceList">
         <team-places :value="form.tagPlaceList" @input="GetTagPlaceList"></team-places>
      </el-form-item>
      <el-form-item :label="$t('common.fields.serviceProviderManager.displayName')" prop="serviceProviderManager">
        <form-user
          :field="filedMap.teamLeaders"
          :isJudge="'dept'"
          v-model="form.serviceProviderManager"
          multiple
          :type-service-provider="1"
          @input="(val) => $refs.form.validateField('serviceProviderManager')"
        />
      </el-form-item>
      <el-form-item :label="$t('common.base.managerPermission')">
        <div class="team-form-role-tip">
          <input type="checkbox" checked disabled />
          {{$t('serviceProvider.managerAutoPermission')}}
        </div>
      </el-form-item>
        <el-form-item :label="$t('common.fields.contact.displayName')" prop="serviceProviderContact">
        <form-user
          :field="filedMap.teamContact"
          :isJudge="'dept'"
          v-model="form.serviceProviderContact"
          :type-service-provider="1"
          @input="(val) => $refs.form.validateField('serviceProviderContact')"
        />
      </el-form-item>
      <el-form-item :label="$t('common.fields.contactNumber.displayName')" prop="linkPhone">
        <el-input
          v-model="form.linkPhone"
          :maxlength="11"
          :placeholder="$t('common.placeholder.inputContactPhone')"
        ></el-input>
      </el-form-item>
      <el-form-item :label="$t('common.fields.weChatId.displayName')" prop="wechat">
        <el-input
          v-model="form.wechat"
          :placeholder="$t('common.placeholder.inputWeChatAccount')"
        ></el-input>
      </el-form-item>
      <el-form-item :label="$t('common.fields.email.displayName')" prop="email">
        <el-input
          v-model="form.email"
          :placeholder="$t('common.placeholder.inputEmail')"
        ></el-input>
      </el-form-item>
      
      <el-form-item :label="$t('common.fields.tags.displayName')" prop="label">
        <el-select v-if="labelList.length > 0" v-model="form.label" :placeholder="$t('common.base.pleaseSelect')" multiple>
          <el-option
            v-for="item in labelList"
            :key="item.id"
            :label="item.tagName"
            :value="String(item.id)"
          >
          </el-option>
        </el-select>

        <div class="label-txt" v-else>
          {{$t('serviceProvider.noTags')}}
        </div>
      </el-form-item>
      <el-form-item :label="$t('common.tabs.additionContractList')" prop="contract">
        <base-upload
          :value="form.contract"
          @input="contractUpload"
          @remove="contractRemove"
        ></base-upload>
      </el-form-item>
      <el-form-item :label="$t('common.fields.skillsCertificate.displayName')" prop="skillCertificate">
        <base-upload
          :value="form.skillCertificate"
          @input="skillCertificateUpload"
          @remove="skillCertificateRemove"
        ></base-upload>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
/* apis */
import { getBaseLabelList } from '@src/api/DepartmentApi';
import { info, searchCompany } from '@src/api/serviceProviderApi';
import FormMixin from '@src/component/form/mixin/form';
import {isArray} from "@src/util/type";
import { validatePhone } from '@src/util/validator'
export default {
  name: 'team-edit-view',
  props: {
    id: {
      type: Number
    }
  },
  watch: {
    id(n, o) {
      if (n) {
        this.getInfo(n);
      } else {
        if (n == 0) {
          this.filterParams.keyword = '';
          this.iptLegalPerson = '';

          this.form = JSON.parse(JSON.stringify(this.initForm()));
        } else {
          this.getInfo(o);
        }
      }
    }
  },
  data() {
    const checName = (rule, value, cb) => {
      if (this.form.ProviderName || this.form.serviceProviderName) {
        if(this.form.ProviderName instanceof Array&&this.form.ProviderName.length == 0&&!this.form.serviceProviderName){
         cb(new Error(this.$t('common.validate.inputServiceProviderName')));
       }
        return cb();
      }
      
      cb(new Error(this.$t('common.validate.inputServiceProviderName')));
    };
    // 验证固话手机号的规则
    const checkEmail = (rule, value, cb) => {
      const regMobile = /^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,5}$/;
      if (!value || regMobile.test(value)) {
        return cb();
      }
      cb(new Error(this.$t('common.validate.checkEmail')));
    };
    // 验证固话手机号的规则
    const checkMobile = (rule, value, cb) => {
      if (!value || validatePhone(value, 3)) {
        return cb();
      }
      cb(new Error(this.$t('common.validate.checkTel')));
    };
    let validateUser = (rule, value, callback) => {
      if(!this.form.serviceProviderManager){
        callback(new Error(this.$t('common.validate.selectServiceProviderMaster')));
      }
      if (this.form.serviceProviderManager && !this.form.serviceProviderManager.length) {
        callback(new Error(this.$t('common.validate.selectServiceProviderMaster')));
      } else {
        callback();
      }
    };
    return {
      is: {
        checked: false // 手动输入
      },
      serviceProviderAttribute: Object.freeze([
        {
          name: this.$t('common.base.directServiceProvider'),
          id: 1
        },
        {
          name: this.$t('common.base.agencyServiceProvider'),
          id: 2
        },
        {
          name: this.$t('common.base.wholeServiceProvider'),
          id: 3
        }
      ]), // 服务商属性
      serviceProviderManager: [
        {
          name: `${this.$t('common.base.executiveDirector')}1`,
          id: 1
        }
      ], // 服务商主管选择列表
      labelList: [], // 标签
      form: {},
      tagName: [],
      filedMap: {
        tagAddress: {
          displayName: this.$t('common.fields.serviceProviderRegisterAddress.displayName'),
          fieldName: 'tagAddress',
          formType: 'address',
          isNull: 1
        },
        teamLeaders: {
          displayName: this.$t('common.fields.serviceProviderManager.displayName'),
          fieldName: 'serviceProviderManager',
          formType: 'user',
          isNull: 0
        },
        teamContact: {
          displayName: this.$t('common.fields.contact.displayName'),
          fieldName: 'serviceProviderContact',
          formType: 'user',
          isNull: 0
        },
      },
      rules: {
        serviceProviderName: [
          { required: true, validator: checName, trigger: ['blur', 'input'] }
        ],
        serviceProviderManager: [
          {
            required: true,
            validator: validateUser,
            trigger: ['blue', 'change']
          }
        ],
        linkPhone: [{ validator: checkMobile, trigger: 'blur' }],
        email: [{ validator: checkEmail, trigger: 'blur' }]
      },
      // 企查查查询
      filterFlag: false,
      filterParams:{
        keyword:'',
        pageNum: 1,
        pageSize: 10
      },
      filterData: {
        list: []
      },
      isEmptyLoading: false,
      iptLegalPerson: '',
      isTime: true
    };
  },
  created() {
    this.getLabelList();
    if (this.id) {
      this.getInfo(this.id);
    }
  },
  methods: {
    // 获取负责地址数据
    GetTagPlaceList(value){
      this.form.tagPlaceList =JSON.parse(JSON.stringify(value))
    },
    treeUpdate(e) {
      this.tagName = e;
    },
    initForm() {
      return {
        ProviderName: [],
        parentId: '', // 父节点ID
        serviceProviderName: '', // 服务商名称
        creditCode: '', // 统一社会信用代码
        serviceProviderAttribute: '', // 服务商属性：直营服务商、授权服务商、销售服务一体商
        registerCompanyName: '', // 注册公司名称
        serviceProviderManager: [], // 服务商主管
        linkPhone: '', // 联系电话
        wechat: '', // 微信号
        email: '', // 邮箱
        legalPerson: '', // 法人代表
        country: '',
        province: '', // 注册地址：省
        city: '', // 注册地址：市
        dist: '', // 注册地址：区
        address: '', // 注册地址：详情地址
        longitude: null, // 注册地址：经度
        latitude: null, // 注册地址：纬度
        label: [], // 标签ID
        contract: [], // 合同
        skillCertificate: [], // 技能证书
        tagAddress: {},
        tagName: [],
        // 负责区域
        tagPlaceList:[],
        // 负责人
        serviceProviderContact:{}
      };
    },
    submit(cb) {
      this.form.legalPerson = this.iptLegalPerson;
      this.form = {
        ...this.form,
        ...this.form.tagAddress
      };
      // 保存负责人不需要是数组的字段
      for(let key in this.form?.serviceProviderContact) {
        if(isArray(this.form.serviceProviderContact[key]))  {
          delete this.form.serviceProviderContact[key]
        }
      }
      this.$refs.form.validate(valid => {
        if (valid) {
          cb(this.form);
          if(this.id === 0){
            this.form = JSON.parse(JSON.stringify(this.initForm()));
          }
        }
      });
    },
    async getInfo(id) {
      let _this = this;
      let params = {
        id
      };
      await info(params).then(r => {
        this.form = r.data;
        this.filterParams.keyword = r.data.registerCompanyName;
        this.iptLegalPerson = r.data.legalPerson;
        
        if (r.data.address) {
          this.form.tagAddress = {};
          this.form.tagAddress.address = r.data.address;
          this.form.tagAddress.addressType = 1;
          this.form.tagAddress.city = r.data.city;
          this.form.tagAddress.dist = r.data.dist;
          this.form.tagAddress.latitude = r.data.latitude;
          this.form.tagAddress.longitude = r.data.longitude;
          this.form.tagAddress.province = r.data.province;
          this.form.tagAddress.country = r.data.country;
        }
        if (this.form.creditCode) {
          if (this.form.serviceProviderName) {
            this.form.ProviderName = [];
            this.form.ProviderName.push({
              label: _this.form.serviceProviderName,
              value: _this.form.creditCode
            });
          }
        } else {
          this.is.checked = true;
        }
        if (!this.form.parentId) this.form.parentId = this.id;
      });
    },

    // 上传
    contractUpload(queue) {
      this.$set(this.form,'contract',queue);
      this.$forceUpdate();
    },

    // 移除上传
    async contractRemove(file) {
      if (!(await this.$platform.confirm(this.$t('common.form.preview.file.deleteFileTips')))) return;

      let index = -1;
      for (let i = 0; i < this.form.contract.length; i++) {
        let f = this.form.contract[i];
        if (f.url == file.url) {
          index = i;
          break;
        }
      }
      if (index >= 0) this.form.contract.splice(index, 1);
      this.$forceUpdate();
    },
    // 上传
    skillCertificateUpload(queue) {
      this.$set(this.form,'skillCertificate',queue);
      this.$forceUpdate();
    },

    // 移除上传
    async skillCertificateRemove(file) {
      if (!(await this.$platform.confirm(this.$t('common.form.preview.file.deleteFileTips')))) return;

      let index = -1;
      for (let i = 0; i < this.form.skillCertificate.length; i++) {
        let f = this.form.skillCertificate[i];
        if (f.url == file.url) {
          index = i;
          break;
        }
      }
      if (index >= 0) this.form.skillCertificate.splice(index, 1);
      this.$forceUpdate();
    },
    getLabelList() {
      getBaseLabelList().then(r => {
        this.labelList = r.data;
      });
    },

    updateCustomer(value) {
      if (!this.is.checked) {
        this.form.ProviderName = value;
        this.form.creditCode = value[0].value;
        this.form.serviceProviderName = value[0].label;
        this.form.legalPerson = value[0].operName;
      } else {
        if (this.form.serviceProviderName != this.form.ProviderName) {
          this.form.creditCode = '';
        }
        if (!this.form.serviceProviderName) {
          this.form.ProviderName = [];
        }
      }
      this.$forceUpdate();
    },

    /**
     * @description 搜索客户
     */
    async searchCustomer(params = {}) {
      this.isEmptyLoading = true;
      if (!params.keyword) {
        params.keyword = this.form.serviceProviderName;
      }
      try {
        let result = await searchCompany(params);
        this.isTime = true;
        this.isEmptyLoading = false;
        if(result.status !== 0) return this.$platform.alert(result.message);
        
        if (result.data) {
          result.data.list = result.data.list.map(product =>({
              label: product.name,
              value: product.creditCode || product.keyNo,
              ...product
            })
          );

          const oldArr = this.filterData.list;
          const newArr = result.data.list;

          this.filterData = result.data;
          this.filterData.list = [...oldArr,...newArr];
        }
      } catch (error) {
        console.warn('task-edit-form: searchCustomer -> error', error);
      }
    },
    async btnFilter(){
      if(!this.isTime) return;
      this.isTime = false;
      
      this.initIptData();
      this.filterFlag = true;

      await this.searchCustomer(this.filterParams);
    },
    async load () {
      if(this.filterData.list.length >= this.filterData.total) return;
      
      this.filterParams.pageNum++;
      this.searchCustomer(this.filterParams);
    },
    getItem(e){
      this.form.ProviderName = [e];
      this.form.creditCode = e.value;
      this.form.registerCompanyName = e.label;
      this.iptLegalPerson = e.operName;
      this.filterParams.keyword = e.label;

      this.filterFlag = false;
    },
    iptBlur(){
      if(this.filterData.list.length > 0){
        this.filterFlag = false;
      }else {
        this.initIptData();
      }
    },
    iptFocus(){
      if(this.filterData.list.length > 0) this.filterFlag = true;
    },
    iptClear(){
      this.initIptData();
      this.filterFlag = false;
    },
    initIptData(){
      this.filterData.list = [];
      this.filterParams.pageNum = 1;
    },
    initKeyVal(){
      this.filterParams.keyword = '';
      this.iptLegalPerson = '';
    }
  },
  components:{
    'team-places': {
      mixins: [FormMixin],
      props: {
        value: {
          type: Array,
          default: () => []
        }
      },
      methods: {
        addPlace() {
          this.value.push({});
          this.$emit('input', this.value);
        },
        removePlace(item) {
          let index = this.value.indexOf(item);
          if (index >= 0) this.value.splice(index, 1);

          this.$emit('input', this.value);
        },
        update(item, value = {}) {
          let {country,province, city, dist} = value;
          this.$set(item, 'country', country);
          this.$set(item, 'province', province);
          this.$set(item, 'city', city);
          this.$set(item, 'dist', dist);

          this.$emit('input', this.value);
        }
      },
      render(h) {
        return (
          <div class="team-form-places">
            <div class="team-form-places-header">
              <p>{this.$t('serviceProvider.autoAllotCustomer')}</p>
              <button
                type="button"
                class="btn-text"
                onClick={e => this.addPlace()}
              >
                <i class="iconfont icon-add" />
                {this.$t('common.base.add2')}
              </button>
            </div>
            {this.value.map((item, index) => (
              <div
                class={['team-form-place', item.success ? 'is-success' : null]}
                key={index}
              >
                <base-dist
                  value={item}
                  onInput={e => this.update(item, e)}
                  showOneLine={true}
                />
                <button
                  type="button"
                  class="btn-text"
                  onClick={e => this.removePlace(item)}
                >
                  {this.$t('common.base.delete')}
                </button>
              </div>
            ))}
          </div>
        );
      }
    },
  }
};
</script>
<style lang="scss">
.add-dialog-container.service_body .el-form.demo-ruleForm.service_form {
  width: 100%;
  box-sizing: border-box;
  padding:10px 24px;
}
.team-form-places-header {
  padding: 4px 0;
  color: $text-color-secondary;
  display: flex;
  flex-flow: row nowrap;

  p {
    flex: 1;
    margin: 0;
  }

  .btn-text {
    color: $color-primary;

    i {
      font-size: 12px;
      margin-right: 5px;
    }
  }
}
</style>

<style lang="scss" scoped>
.el-select {
  width: 100%;
}
.label-txt {
  color: $color-warning;
}
.action-btn {
  margin-left: 10px;
}
.infinite-box {
  width: calc(100% - 98px);
  position: absolute;
  left: 0;
  top: 35px;
  z-index: 999;
  background-color: #fff;

  border: 1px solid #e4e7ed;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
  box-sizing: border-box;
  margin: 5px 0;
}
.infinite-list {
  max-height: 274px;
  list-style: none;
  padding: 6px 0;
  margin: 0;
  box-sizing: border-box;
  background-color: #fff;
}
.infinite-list li {
  width: 100%;
  font-size: 14px;
  padding: 0 20px;
  position: relative;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  color: #606266;
  height: 34px;
  line-height: 34px;
  box-sizing: border-box;
  cursor: pointer;
}
.infinite-list li:hover {
  background-color: #f5f7fa;
}
.register-empty {
  padding: 10px 0;
  margin: 0;
  text-align: center;
  color: #999;
  font-size: 14px;
}
</style>